/**
  ******************************************************************************
  * @file    bms_hal_monitor.c
  * @author  Forester
  * @brief   
  ******************************************************************************
  * @attention
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "bms_monitor.h"
#include "bms_hal_monitor.h"
#include "drv_softi2c_bq769x0.h"
#include "universal_util.h"
#include "bms_global.h"

#include "freertos.h"

/* Export variable------------------------------------------------------------*/


// 冒泡排序的比较程序,对电压数据进行比较
static int compaer_cell(void *e1, void *e2)
{
	float temp1, temp2;
	
	temp1 = (*(BMS_CellDataTypedef *)e1).CellVoltage;
	temp2 = (*(BMS_CellDataTypedef *)e2).CellVoltage;

	if (temp1 > temp2)
	{
		return 1;
	}

    return 0;
}

// 采集单体电压
void Bms_HalMonitorCellVoltage(void)
{
	// 数据先存放到 BQ 驱动层的 SampleData 中
	BQ769X0_UpdateCellVolt();
	
	// 计算转化到 BMS_MonitorData 中
	for (uint8_t index = 0; index < BMS_GlobalParam.Cell_Real_Number; index++)
	{
		BMS_MonitorData.CellVoltage[index] = BQ769X0_SampleData.CellVoltage[index];
		BMS_MonitorData.CellData[index].CellVoltage = BQ769X0_SampleData.CellVoltage[index];
		BMS_MonitorData.CellData[index].CellNumber  = index;
	}
	
	// 排序
	BubbleSort(BMS_MonitorData.CellData, BMS_CELL_MAX, sizeof(BMS_CellDataTypedef), compaer_cell);
}


// 采集电池组电压
void BMS_HalMonitorBatteryVoltage(void)
{
	BQ769X0_UpdateBatVoltage();
	BMS_MonitorData.BatteryVoltage = BQ769X0_SampleData.BatteryVoltage;
}

// 采集电池温度
void BMS_HALMonitorCellTemperature(void)
{
	uint8_t index1 = 0, index2 = 0;
	BQ769X0_UpdateTsTemp();
	
	// 只取有效 NTC 的温度
	for(; index1 < BMS_GlobalParam.Cell_Real_Number; index1++)
	{
		if(BQ769X0_SampleData.TsxTemperature[index1] >= BMS_TEMP_MEASURE_MIN && BQ769X0_SampleData.TsxTemperature[index1] <= BMS_TEMP_MEASURE_MAX)
		{
			BMS_MonitorData.CellTemp[index2++] = BQ769X0_SampleData.TsxTemperature[index1];
		}
	}
	BMS_MonitorData.CellTempEffectiveNumber = index2;
	
	// 逆序排序
	BubbleFloat(BMS_MonitorData.CellTemp, index2);
}

// 采集电流
void Bms_HalMonitorBatteryCurrent(void)
{
	BQ769X0_UpdateCurrent();
	BMS_MonitorData.BatteryCurrent = BQ769X0_SampleData.BatteryCurrent;
	// printf("Battery Current = %f\r\n", BMS_MonitorData.BatteryCurrent);
}
